import React, { useState } from 'react';
import { userAPI } from '../../services/api';
import { setAuthToken } from '../../services/auth';
import '../styles/auth.css';

interface LoginProps {
  onLoginSuccess: () => void;
  onGoToRegister: () => void;
}

const Login: React.FC<LoginProps> = ({ onLoginSuccess, onGoToRegister }) => {
  const [username, setUsername] = useState<string>('');
  const [password, setPassword] = useState<string>('');
  const [error, setError] = useState<string>('');
  const [isLoading, setIsLoading] = useState<boolean>(false);

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    
    if (!username || !password) {
      setError('请输入用户名和密码');
      return;
    }

    console.log('Login attempt with username:', username);
    console.log('Password length:', password.length > 0 ? '****' : 'empty');

    try {
      setIsLoading(true);
      const response = await userAPI.login(username, password);
      
      console.log('API response:', response);
      
      if (response.success && response.data?.token) {
        console.log('Login successful, token obtained');
        setAuthToken(response.data.token);
        onLoginSuccess();
      } else {
        console.log('Login failed:', response.message);
        setError(response.message || '登录失败，请检查用户名和密码');
      }
    } catch (err) {
      setError('登录失败，请稍后重试');
      console.error('Login error:', err);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="auth-container">
      <div className="auth-card">
        <h2>登录 - 一念之间</h2>
        <form onSubmit={handleLogin} className="auth-form">
          <div className="form-group">
            <label htmlFor="username">用户名</label>
            <input
              type="text"
              id="username"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              placeholder="请输入用户名"
              disabled={isLoading}
            />
          </div>
          <div className="form-group">
            <label htmlFor="password">密码</label>
            <input
              type="password"
              id="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="请输入密码"
              disabled={isLoading}
            />
          </div>
          {error && <div className="error-message">{error}</div>}
          <button 
            type="submit" 
            className="auth-button"
            disabled={isLoading}
          >
            {isLoading ? '登录中...' : '登录'}
          </button>
          <div className="auth-link">
            还没有账号？ <span onClick={onGoToRegister}>立即注册</span>
          </div>
        </form>
      </div>
    </div>
  );
};

export default Login;